package com.bojx.cms.interceptor;

import com.bojx.cms.util.EncryptUtil;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;

/**
 * 
 * @author syh this inteceptor is used to check login
 *
 */
public class LoginIntercepter implements Interceptor {

	@Override
	public void intercept(Invocation inv) {
		Controller controller = inv.getController();
		String username = controller.getCookie("username");
		String ssid = controller.getCookie("ssid");
		if (username == null || ssid == null || !EncryptUtil.md5(username).equals(ssid)) {
			String isAjax = controller.getRequest().getHeader("X-Requested-With");
			if (isAjax != null && isAjax.equalsIgnoreCase("XMLHttpRequest")) {
				Record result=new Record();
				result.set("code", "302");
				result.set("msg","请先登录");
				controller.render(new JsonRender(result).forIE());
			} else {
				controller.redirect("/login/index?sendURL=" + controller.getRequest().getRequestURI());
			}
		} else {
			inv.invoke();
		}

	}
}
